<?php

namespace App\Http\Controllers\Course;

use App\Events\Share;
use App\Http\Controllers\BaseController;
use App\Models\Course;
use App\Models\CourseChapter;
use App\Models\CourseOrder;
use App\Models\User;
use App\Models\UserPointsDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Yansongda\Pay\Pay;

class CourseController extends BaseController
{
    public function index(Request $request)
    {
       $param = $this->validate($request,[
           'user_id' => 'integer',
           'order_type' => 'in:study',
           'keyword' => 'string|max:100'
       ]);

       $query = Course::query()
                    ->selectRaw('*,(select sum(view_count) from course_browses where course_id=courses.id) as view_count');

       $user_id = auth('api')->id();

       if (isset($param['user_id'])){
           $query->where('user_id',$param['user_id']);
       }

        if (isset($param['keyword'])){
            $query->where('name','like','%'.$param['keyword'].'%');
        }

       if (isset($param['order_type'])){
           $query->orderByDesc('study_count');
       }else{
           $query->orderBy('sort')
               ->orderByDesc('id');
       }

       $data = $query->with('auth:user_id,name')
            ->where('audit_status',2)
            ->where('status',1)
            ->withCount('chapter')

            ->simplePaginate(10);

       return $this->success($data);
    }

    public function share(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer'
        ]);

        $user_id = auth('api')->id();
        $share_id  = DB::table('course_shares')
            ->where('user_id',$user_id)
            ->where('course_id',$param['course_id'])
            ->whereDate('share_time',date('Y-m-d'))
            ->value('id');

        if (!$share_id){
            $result = DB::table('course_shares')->insert([
                'user_id' => $user_id,
                'course_id' => $param['course_id'],
                'share_count' => 1,
                'share_time' => date('Y-m-d H:i:s')
            ]);
        }else{
            $result = DB::table('course_shares')
                ->where('id',$share_id)
                ->increment('share_count');
        }

        event(new Share($user_id));


        return $result ? $this->success() : $this->error();
    }

    public function status(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer'
        ]);

        $is_buy = DB::table('course_orders')
                    ->where('course_id',$param['course_id'])
                    ->where('status',2)
                    ->exists();

        return $this->success(['is_buy' => $is_buy]);
    }


    public function chapter(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer'
        ]);

        $data = CourseChapter::query()
                    ->where('course_id',$param['course_id'])
                    ->get();

        return $this->success($data);
    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'firm_profession_id'=>'required|integer',
            'cover' => 'required',
            'name' => 'required|max:255',
            'content' => 'required',
            'price' => 'required_if:sale_type,1',
            'points' => 'required_if:sale_type,2',
            'sale_type' => 'required|in:1,2,3'
        ]);

        $param['user_id'] = auth('api')->id();
        $course = Course::query()->create($param);



        if ($course->getKey()){
            return $this->success(['course_id' => $course->getKey()]);
        }

        return  $this->error();
    }

    public function show(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer'
        ]);

        $user_id = auth('api')->id();
        $data = Course::query()
                    ->selectRaw('*,(select sum(share_count) from course_shares where course_id=courses.id) as share_count,
                    (select sum(view_count) from course_browses where course_id=courses.id) as view_count,(select count(id) from user_like_courses where user_id='.$user_id.' and course_id=courses.id and status=1) as user_is_like,
                    (select count(id) from user_collect_courses where user_id='.$user_id.' and course_id=courses.id and status=1) as user_is_collect')
                    ->withCount('chapter')
                    ->with(['user:id,avatar,nickname,user_title_id','identity'])
                    ->withCount(['comment' => function($q){
                        $q->where('audit_status',2);
                    }])->withCount(['collect' => function($q){
                        $q->where('status',1);
                    }])->withCount(['like' => function($q){
                        $q->where('status',1);
                    }])->withCount(['order' => function($q) use ($user_id){
                       $q->where('status',2)->where('user_id',$user_id);
                    }])->where('id',$param['course_id'])
                    ->first();

        return $this->success($data);

    }

    public function update(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer',
            'firm_profession_id'=>'required|integer',
            'cover' => 'required',
            'name' => 'required|max:255',
            'content' => 'required',
            'price' => 'required_if:sale_type,1',
            'points' => 'required_if:sale_type,2',
            'sale_type' => 'required|in:1,2,3',
        ]);

        $param['user_id'] = auth('api')->id();
        $course_id = $param['course_id'];
        unset($param['course_id']);
        $result = Course::query()->where('id',$course_id)->update($param);
        return  $result ? $this->success() : $this->error();
    }



    public function delete(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer'
        ]);

        $result = Course::query()->where('id',$param['course_id'])->delete();
        CourseChapter::query()->where($param)->delete();

        return $result ? $this->success() : $this->error();
    }
}
